package cn.toolck.service.impl;

import cn.toolck.dao.LagouAuthCodeDao;
import cn.toolck.pojo.LagouAuthCode;
import cn.toolck.service.EmailService;
import cn.toolck.service.LagouAuthCodeService;
import cn.toolck.user.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;

import java.util.*;

@Service
public class LagouAuthCodeServiceImpl implements LagouAuthCodeService {
    @Autowired
    private LagouAuthCodeDao lagouAuthCodeDao;

    @Reference
    private EmailService emailService;

    @Reference
    private UserService userService;

    /**
     * 校验验证码是否正确，
     *
     * @param email 邮箱
     * @param code  验证码
     * @return 0正确1错误2超时
     */
    @Override
    public int validate(String email, String code) {
        Optional<LagouAuthCode> lagouAuthCodeOptional = isPresent(email);
        boolean result = lagouAuthCodeOptional.isPresent()
                && Objects.equals(code, lagouAuthCodeOptional.get().getCode());
        if (!result) {
            return 1;
        }
        if (lagouAuthCodeOptional.get().getExpiretime().before(new Date())) {
            return 2;
        }
        return 0;
    }

    /**
     * ⽣成验证码并发送到对应邮箱
     *
     * @param email 邮箱
     * @return 成功true，失败false
     */
    @Override
    public Boolean createAndSend(String email) {
        if (userService.isRegistered(email)) {
            return false;
        }
        String code = create(email);
        return send(email, code);
    }


    /**
     * 创建验证码并落库
     *
     * @param email 邮箱
     * @return 验证码
     */
    @Override
    public String create(String email) {
        Optional<LagouAuthCode> lagouAuthCodeOptional = isPresent(email);
        LagouAuthCode lagouAuthCode = null;
        String code = UUID.randomUUID().toString().substring(0, 4);
        if (lagouAuthCodeOptional.isPresent()) {
            lagouAuthCode = lagouAuthCodeOptional.get();
            lagouAuthCode.flush(code);
        } else {
            lagouAuthCode = new LagouAuthCode(code, email);
        }
        // 生成验证码
        lagouAuthCodeDao.save(lagouAuthCode);
        return code;
    }

    @Override
    public Boolean send(String email, String code) {
        Boolean result = emailService.sendCode(email, code);
        return result;
    }


    /**
     * 查看LagouAuthCode中是否存在email
     *
     * @param email 邮箱
     * @return LagouAuthCode对象的Optional
     */
    @Override
    public Optional<LagouAuthCode> isPresent(String email) {
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        Example<LagouAuthCode> of = Example.of(lagouAuthCode);
        return lagouAuthCodeDao.findOne(of);
    }
}
